import Fuse from 'fuse.js';
import { pinyin } from 'pinyin-pro';

export function normalize(str) {
  return (str || '').toString().trim().toLowerCase();
}

// 为中文生成拼音和首字母，英文则原样
export function toPinyin(str) {
  const s = (str || '').toString().trim();
  if (!s) return { full: '', first: '' };
  try {
    const full = pinyin(s, { toneType: 'none', type: 'array' }).join(' ');
    const first = pinyin(s, { pattern: 'first', toneType: 'none', type: 'array' }).join('');
    return { full: normalize(full), first: normalize(first) };
  } catch {
    return { full: normalize(s), first: normalize(s) };
  }
}

// 构建 Fuse 实例（标题/别名/演员 支持）
export function buildFuse(movies) {
  return new Fuse(movies, {
    includeScore: true,
    threshold: 0.35,
    keys: [
      'title',
      'aliases',
      'actors'
    ]
  });
}

// 命中逻辑：关键字、别名、演员、拼音（全拼/首字母）
export function matchKeyword(movie, q) {
  if (!q) return true;
  const needle = normalize(q);
  const fields = [
    movie.title,
    ...(movie.aliases || []),
    ...(movie.actors || [])
  ].map(normalize);

  const pinyins = [
    toPinyin(movie.title),
    ...(movie.aliases || []).map(toPinyin),
    ...(movie.actors || []).map(toPinyin)
  ];

  if (fields.some(f => f.includes(needle))) return true;
  if (pinyins.some(p => p.full.includes(needle) || p.first.includes(needle))) return true;
  return false;
}

// 联想：返回影片/演员/tag（类型）建议
export function buildSuggestions(movies, q, limit = 8) {
  const needle = normalize(q);
  if (!needle) return [];
  const set = new Set();

  movies.forEach(m => {
    const fields = [
      m.title, ...(m.aliases || []), ...(m.actors || []), ...(m.genres || [])
    ];
    fields.forEach(f => {
      const s = normalize(f);
      const { full, first } = toPinyin(f);
      if (s.includes(needle) || full.includes(needle) || first.includes(needle)) {
        set.add(f);
      }
    });
  });

  return Array.from(set).slice(0, limit);
}